package com.gzsxy.JUC;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * lock锁
 */
public class SaleTickDemo1 {

    public static void main(String[] args) {
        //并发：多个线程操作同一个资源类,把资源丢入到线程
        Ticket ticket = new Ticket();

        //匿名内部类直接new 接口Runable   最后简化为（）
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "A").start();


        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "B").start();


        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "C").start();
    }


}

/**
 * lock三部曲
 * new Reentrantlock（）
 * lock.lock  //枷锁
 * finally
 */
class Ticket1 {
    private int number = 50;

    //定义lock锁
    Lock lock = new ReentrantLock();


    public void sale() {
        lock.lock();
//        //尝试获取锁
//        lock.tryLock();


        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了" + (number--) + "票" + "剩余" + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}